/**
 * 获取用户信息和权限
 * @param {*} data 数据
 * @param {*} id 用户id
 */
function getIdentiAndLimits(data, id){
    var identiAndLimits = {};
    data.identitys.forEach(function(identity){
        if(identity.id === id){
            identiAndLimits.text = identity.text;
            var limits = identity.limits;
            identiAndLimits.limits = [];
            data.currUserLimits = [];
            // 遍历数据文件中所有的权限，并添加到用户权限中
            data.limits.forEach(function(limit){
                if(limits.indexOf(limit.lid) !== -1 ){
                    identiAndLimits.limits.push(limit);
                    // 存储在
                    data.currUserLimits.push(limit.page);
                }
            });
            return identiAndLimits;
        }
    });
    return identiAndLimits ;
}

module.exports = function(data){
    return function(req, resp, next){
        var _username = req.body.username;
        var _password = req.body.password;
        var isFind = false;
        data.users.forEach(function(user){
            if(user.username === _username 
                && user.userpwd === _password) {
                
                isFind = true;
                var _id = user.id;
                var identiAndLimits = getIdentiAndLimits(data, _id);
                console.log("执行了首页渲染");
                var indexPageInfo = {'title': '首页', 'username':_username, 'text': identiAndLimits.text, 'limits':identiAndLimits.limits };
                data.indexPageInfo = indexPageInfo;
                resp.render('index', indexPageInfo);
                return;
            }
        });
        if(!isFind){
            data.currUserLimits = [];
            next(new Error('用户名或密码错误'));
        }
    }
}